package com.skyeyes.controller;

import com.skyeyes.constant.MessageConstant;
import com.skyeyes.result.Result;
import com.skyeyes.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {


    @Autowired
    private CommonService commonService;




    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("uploadImage") MultipartFile file){
        log.info("文件上传: {}",file);

        try {
            String originalFilename = file.getOriginalFilename();
            String extention = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName=UUID.randomUUID()+extention;
            log.info(originalFilename);
            log.info(file.getName());

            long size = file.getSize();
            log.error("文件大小:"+size);
            String totalSize=(size/1024/1024)+ "MB";
            return Result.success(originalFilename+":"+totalSize);
        } catch (Exception e) {
            log.error("文件上传失败");

        }
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }

    @GetMapping("/test")
    public Result<String> upload(){
        return Result.success("请求成功");
    }


    @GetMapping("/randomcode")
    public Result<String> getRandomCode(){
        String code=commonService.getRandomCode();
        return Result.success(code);
    }

    private String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            long size = f.length();
            return (size / 1024f) / 1024f + "MB";
        }
    }






















}
